<template>
  <!-- 我的回收线索 -->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="68px">
      <el-form-item label="来源" prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择" clearable>
          <el-option label="回收链接" :value="1" />
          <el-option label="竞拍" :value="2" />
           <el-option label="竞价回收" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="回收状态" prop="backState">
        <el-select v-model="queryParams.backState" placeholder="请选择" clearable>
          <el-option :label="item.label" :value="key" v-for="(item,key) in commonMaps.backStateMap" :key="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="游戏类型" prop="gameId">
        <el-select v-model="queryParams.gameId" placeholder="请选择游戏" clearable>
          <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="账号" prop="accountNumber">
        <el-input v-model="queryParams.accountNumber" placeholder="请输入账号" clearable />
      </el-form-item>
      <el-form-item label="简介" prop="des">
        <el-input v-model="queryParams.des" placeholder="请输入关键字" clearable />
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button icon="el-icon-refresh" type="primary" plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="table_box" v-loading="loading">
      <el-table :data="tableData.records" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>

        <el-table-column prop="source" label="来源" width="80">
          <template slot-scope="scope">
            <el-tag type="warning" v-show="scope.row.source==1">回收链接</el-tag>
            <el-tag type="" v-show="scope.row.source==2">竞拍</el-tag>
             <el-tag type="success" v-show="scope.row.source==4">竞价回收</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="actived == '已拒收'" prop="rmsg" label="拒收原因" width="120"></el-table-column> -->

        <el-table-column prop="gameName" label="游戏名称" width="120"></el-table-column>
        <el-table-column prop="region" label="区服" min-width="100"></el-table-column>

        <el-table-column prop="accountNumber" label="游戏账号" width="100"></el-table-column>
        <!-- <el-table-column prop="relname" label="实名" width="100"></el-table-column> -->

        <!-- isAgreeBp -->
        <el-table-column prop="des" label="商品详情" min-width="200">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.des" placement="top-start">
              <div class="zdy-des">{{ scope.row.des }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="160"></el-table-column>
        <el-table-column prop="hopeAmount" label="期望价" width="100"></el-table-column>
        <!-- hopeAmount -->
        <el-table-column prop="gujiaAmount" label="AI估价" width="100">
          <template slot-scope="scope">
            <div>
              {{scope.row.gujiaAmount?scope.row.gujiaAmount:'暂无AI估价'}}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="backAmount" label="回收价" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.source==2 || scope.row.source==4">
              {{scope.row.backAmount?scope.row.backAmount:'暂无回收价'}}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="" label="黑号提示" width="100">
          <template slot-scope="scope">
            <el-tag type="danger" v-show="scope.row.isBlack==1">{{ scope.row.isBlack==1?'黑号':'' }}</el-tag> 
          </template>
        </el-table-column> -->

        <!-- <el-table-column prop="btime" label="报价时间" width="160" v-if="actived == '已报价'"></el-table-column> -->
        <!-- <el-table-column prop="status" label="报价状态" width="100" >
              </el-table-column> -->
        <el-table-column prop="backState" label="回收状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="commonMaps.backStateMap[scope.row.backState||1].type">{{commonMaps.backStateMap[scope.row.backState||1].label}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" v-hasPermi="['backClue:viewDetail']" @click="viewBackInfo(scope.row)">查看</el-button>
            <el-button type="text" v-if="scope.row.backState==1 && checkPermi(['backClue:AI'])" @click="AIgujia(scope.row)">AI估价</el-button>
            <el-button type="text" v-if="checkPermi(['backClue:lianxi'])&&scope.row.backState==1&&scope.row.source!=4" @click="goIM(scope.row)">立即联系</el-button>
            <el-button type="text" v-if="checkPermi(['backClue:kaishihuishou'])&&scope.row.backState==1" @click="createOrder(scope.row)">开始回收</el-button>
            <el-button type="del" v-if="checkPermi(['backClue:jushou'])&&scope.row.backState==1&&scope.row.source==1" @click="refuse(scope.row)">拒收</el-button>
            <el-button type="text" v-if="checkPermi(['jingpaishichang:fabujingpai'])&&scope.row.source==1&&scope.row.backState==1" @click="fabujingpai(scope.row.id)">发布到竞拍市场</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <myHuishouDetail ref="myHuishouDetail"></myHuishouDetail>
    <createBackOrder ref="createBackOrder" @close="createBackOrderClose"></createBackOrder>

    <div class="gujiadialog">
      <el-dialog title="选择估价公式" :visible.sync="gujiaDialogShow" width="500px" top="300px">
        <label>
          <b>估价公式：</b>
          <el-select v-model="selectGongshiId" placeholder="请选择估价公式">
            <el-option v-for="(item,i) in gujiaGongshiList" :key="i" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </label>
        <div class="center">
          <el-button @click="gujiaDialogShow = false;selectGongshiId = ''">取 消</el-button>
          <el-button type="primary" @click="AIgujiaDone">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <kefu-list ref="kefuList"></kefu-list>
  </div>
</template>

<script>
import myHuishouDetail from "../components/myHuishouDetail.vue";
import onSelfApi from "@/api/retrieveManage/onSelf.js";
import baopeiApi from "@/api/retrieveManage/baopei.js";
import gameListApi from "@/api/gameConfig/gameList";
import createBackOrder from "../components/createBackOrder.vue";
import { getHXUserInfoByUserId } from "@/api/system/user";
import { listAccount } from "@/api/info/check.js";
import { mapGetters } from "vuex";
import { tenantFormulaSettingsList } from "@/api/equation/equation";

import kefuList from "@/components/common/kefuList.vue";
export default {
  name: "MyHuishou",
  components: {
    myHuishouDetail,
    createBackOrder,
    kefuList,
  },
  data() {
    return {
      gujiaDialogShow: false,
      gujiaGongshiList: [],
      selectGongshiId: "",
      currentRow: {},
      gameList: [], //全部游戏
      loading: false,
      tableData: {
        records: [],
        total: 0,
      },
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        source: "",
        backState: "",
        gameId: "",
        accountNumber: "",
        des: "",
        transfer:1
      },
      pageType: "",
      h5BasicUrl: "",
      currentData: {},
      isHuishouRole: true,
      isTeshu: false,
      openId:'',
      createBackOrderOpen:false
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  created() {
    this.getGameList();
    this.getList();
  },
  watch: {
    $route: {
      handler(newVal) {
        if (newVal.path=="/recycleManage/myHuishou"&&newVal.query&&newVal.query.openId&&this.openId!=newVal.query.openId&&!this.createBackOrderOpen) {
          this.openId = newVal.query.openId
          this.$nextTick(() => {
            this.openDetail(this.openId);
          });
        } else {
          
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    createBackOrderClose(){
      // 关闭下单窗口
      this.createBackOrderOpen = false
      if(this.$route.query&&this.$route.query.openId){
        this.$router.replace({
          path:'/recycleManage/myHuishou'
        })
      }
    },
    // 获取全部游戏
    async getGameList() {
      let res = await gameListApi.getGameList();
      // //console.log("%c Line:278 🍫 res", "color:#465975", res);
      this.gameList = res.rows;
    },
    async openDetail(id){
      const res = await onSelfApi.getBackClueInfo(id)
      console.log("%c Line:218 🍷 res.data", "color:#2eafb0", res.data);
      this.createBackOrderOpen = true
      if(res.data ){
        if(res.data.source == 2) {
          // 竞拍不校验包赔资料
          this.$refs.createBackOrder.open(res.data, '',true);
        }else if(res.data.source == 4) {
          const shiming = await this.getByTypeAndBusinessId(res.data.createId);
          this.$refs.createBackOrder.open(res.data, shiming);
        }
        
      }
    },
    // 获取列表
    getList() {
      this.loading = true;
      // this.queryParams.status = 0;
      // this.queryParams.createId = this.userInfo.userId;
      onSelfApi.getBackClueList(this.queryParams).then((response) => {
        this.tableData.records = response.rows;
        this.tableData.total = response.total;
        this.loading = false;
      });
    },

    // 搜索
    search() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 查看
    viewBackInfo(row) {
      this.$refs.myHuishouDetail.open(row);
    },
    // 立即联系卖家
    async goIM(row) {
      try {
        const { rows } = await listAccount({
          customer: this.userInfo.userId,
          typeArr: [2],
          imCustom: 2,
          imSystem: 2,
          state: 0,
        });
        if (rows && rows.length) {
          // 当前用户开通了客服IM
          // 查询对方环信ID
          if (row.source == 2) {
            // 竞拍的
            // 打开客服列表
            this.$refs.kefuList.open(row.sourceTenantId, 4,{
              gameId:row.gameId,
              gameName:row.gameName,
            });
            // const res2 = await listAccount({
            //   customer: row.createId,
            //   typeArr: [1],
            //   imCustom: 2,
            //   imSystem: 2,
            //   state: 0,
            // });
            // if (res2.rows && res2.rows.length) {
            //   if (res2.rows[0].hxname) {
            //     let obj = {
            //       type: "goChat",
            //       hxusername: res2.rows[0].hxname,
            //       chatType: "singleChat",
            //     };
            //     // 告诉IM系统，需要跳转聊天页
            //     this.$store.dispatch("postMsgToIM", obj);
            //   }
            // }else{
            //   this.$message.error("对方没有开通即时通讯服务，不能聊天！");
            // }
          } else {
            getHXUserInfoByUserId({ id: row.createId }).then((res) => {
              if (res.data.hxusername) {
                let obj = {
                  type: "goChat",
                  hxusername: res.data.hxusername,
                  chatType: "singleChat",
                };
                // 告诉IM系统，需要跳转聊天页
                this.$store.dispatch("postMsgToIM", obj);
              }
            });
          }
        } else {
          //
          this.$message.error("你没有开通即时通讯服务，不能聊天！");
        }
      } catch (error) {}
    },
    // 获取估价公式
    getGongshiList(gameId) {
      tenantFormulaSettingsList({
        gameId: gameId,
      }).then((res) => {
        console.log("%c Line:231 🌽 res", "color:#ed9ec7", res);
        this.gujiaGongshiList = res.rows;
      });
    },
    // AI估价 打开公式列表选择
    AIgujia(row) {
      this.selectGongshiId = "";
      this.currentRow = row;
      this.getGongshiList(row.gameId);
      this.gujiaDialogShow = true;
    },
    // 估价
    AIgujiaDone() {
      if (!this.selectGongshiId) {
        return this.$alert("请选择估价公式！");
      }
      onSelfApi
        .backCluegujia({
          id: this.currentRow.id,
          tenantFormulaSettingsId: this.selectGongshiId,
        })
        .then((res) => {
          this.gujiaDialogShow = false;
          this.$alert(
            `估价结果：${
              res.data.gujiaAmount
                ? "估价成功！AI价格：¥" + res.data.gujiaAmount
                : "暂无AI估价，请设置估价公式！"
            }`
          );
          this.getList();
        })
        .catch((err) => {
          this.gujiaDialogShow = false;
          this.$alert(`估价失败！请检查估价公式是否正确！`);
        });
    },
    // 查询包赔认证信息
    async getByTypeAndBusinessId(row) {
      try {
        const res = await baopeiApi.getByTypeAndBusinessId({
          type: 1,
          businessId: row.createId,
        });
        if (res.data) {
          return res.data;
        } else {
          return false;
        }
      } catch (error) {
        return false;
      }
    },
    // 发布到竞拍市场
    fabujingpai(id){
      this.$confirm("确认将该商品发布到竞拍市场吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          onSelfApi.backClueToJingpai({
            id
          }).then(res=>{
            if(res.code==200){
              this.$alert("成功发布到竞拍市场！请在竞拍市场>我的发布查看。");
            }
          })
        })
        .catch(() => {});
    },
    // 自己回收  开始回收  打开创建回收订单弹窗
    async createOrder(row) {
      if (row.source == 1 ||row.source == 4 ) {
        const shiming = await this.getByTypeAndBusinessId(row);
        // if (!shiming) {
        //   return this.$alert("该用户未进行包赔认证，请先让用户进行包赔认证！");
        // }
        this.$refs.createBackOrder.open(row, shiming);
      }else {
        // 竞拍不校验包赔资料
        this.$refs.createBackOrder.open(row, '',true);
      }
    },

    // 我的回收-拒收
    refuse(row) {
      this.$prompt("请输入拒收原因", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(({ value }) => {
          let obj = {
            id: row.id,
            jushouRemark: value,
          };
          onSelfApi.backClueJushou(obj).then((res) => {
            //console.log("%c Line:518 🍎拒收-我的回收 res", "color:#ea7e5c", res);
            if (res.code == 200) {
              this.getList();
              this.$message({
                type: "success",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {});
    },
    //重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        source: "",
        backState: "",
        gameId: "",
        accountNumber: "",
        des: "",
        transfer:1
      };
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.zdy-des {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  margin: 6px 0;
}
::v-deep .gujiadialog .el-dialog {
  margin-top: 300px !important;
}
.center {
  margin-top: 30px;
}
</style>
